import React, {Component} from 'react';
import CommentAdd from '../comment-add/comment-add'
import CommentList from '../comment-list/comment-list'
import PubSub from 'pubsub-js';

export default class App extends Component {

    // 给组件对象指定state属性
    state = {
        comments: [
            {username: "Tom", content: "React挺好的！"},
            {username: "Jack", content: "React太难了"}
        ]
    }

    // 订阅评论的添加
    componentDidMount() {
        // 订阅添加评论的topic
        PubSub.subscribe("addComment", (msg, comment) => {
            // 更新state的数据
            // 获取当前的数据
            let {comments} = this.state;
            comments.unshift(comment);
            // 更新状态
            this.setState({comments})
        });

        // 订阅删除评论的topic
        PubSub.subscribe("deleteCommentIndex", (msg, index) => {
            let {comments} = this.state;

            comments.splice(index, 1); // splice() 增删改都能做
            // comments.splice(index, 0,{}); // 增加
            // comments.splice(index, 1,{}); // 替换
            // 更新状态
            this.setState({comments})
        })
    }

    render() {
        const {comments} = this.state;
        return (
            <div>
                <header className="site-header jumbotron">
                    <div className="container">
                        <div className="row">
                            <div className="col-xs-12">
                                <h1>请发表对React的评论</h1>
                            </div>
                        </div>
                    </div>
                </header>
                <div className="container">
                    <CommentAdd/>
                    <CommentList comments={comments}/>
                </div>
            </div>
        )
    }
};